package com.ltu.timkor6.gamesite.listings.client;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.ltu.timkor6.gamesite.games.missingbits.client.MissingBitsService;
import com.ltu.timkor6.gamesite.shared.Result;

public class Listings
{
	private ListingsComposite composite;
	
	private ListingsServiceAsync service = GWT.create(ListingsService.class);
	
	public Listings(boolean all)
	{
		checkUser();
		composite = new ListingsComposite(this);
		getListing(all);
	}
	
	/**
	 * For user authentification
	 */
	public void checkUser()
	{
		// Initialize the service proxy.
		if(service == null)
		{
			service = GWT.create(MissingBitsService.class);
		}
		
		// Set up the callback object.
		AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>()
		{
			public void onFailure(Throwable caught)
			{
				Window.alert("Error: " + caught.getMessage());
			}
			
			public void onSuccess(Boolean signedIn)
			{
			}
		};
		
		// Make the call to the stock price service.
		service.checkUser(callback);
	}
	
	/**
	 * Send request for a new query.
	 */
	public void getListing(final boolean all)
	{
		// Initialize the service proxy.
		if(service == null)
		{
			service = GWT.create(ListingsService.class);
		}
		
		// Set up the callback object.
		AsyncCallback<List<Result>> callback = new AsyncCallback<List<Result>>()
		{
			public void onFailure(Throwable caught)
			{
				Window.alert("Error: " + caught.getMessage());
			}
			
			public void onSuccess(List<Result> result)
			{
				if(all)
				{
					composite.drawListsNames(result);
				}
				else
				{
					composite.drawLists(result);
				}
			}
		};
		
		// Make the call to the stock price service.
		service.listings(all, callback);
	}
	
	/**
	 * Return the composite for this game.
	 * @return
	 */
	public Composite getComposite()
	{
		return composite;
	}
}
